<template>
  <div>
    <div class="HotMachineCollapse" :style="lang==='zh'? 'max-width:900px;':'max-width:1100px'">
      <el-form ref="form" label-position="left" :inline="true" :model="record" :label-width="lang==='zh'? '100px':'120px'" :rules="rules" :style="lang==='zh'? 'width:900px;margin:0px auto;':'1100px;margin:0px auto;'">
        <div style="padding: 0 30px;">
          <el-divider content-position="left">{{$t('基本信息')}}</el-divider>
          <el-form-item :label="$t('热备模式')" prop="func_mode" style="width:400px">
            <el-select v-model="record.func_mode" :placeholder="$t('请选择')" size='small' filterable @change="funcModeChange" :disabled='hotState !== "1"'>
              <el-option :id="`hot-machine-func_mode-${key}`" v-for="(item, key) in funcModeList" :key="key" :label="item" :value="key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('抢占模式')" prop="run_mode" v-if="record.func_mode === 'AS'" style="width:400px">
            <el-select v-model="record.run_mode" placeholder="请选择" size='small' filterable disabled>
              <el-option :id="`hot-machine-run_mode-${key}`" v-for="(item, key) in runModeList" :key="key" :label="item" :value="key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('主备模式')" prop="node" v-if="record.func_mode === 'AS'" style="width:400px">
            <el-radio-group v-model="record.node">
              <el-radio label="MASTER">{{$t('主模式')}}</el-radio>
              <el-radio label="BACKUP">{{$t('备模式')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="state" style="width:400px" v-if="record.func_mode === 'AS'">
            <template slot="label">
              {{$t('主备状态')}}<i class="el-icon-info stateIcon" @click="stateClick"></i>
            </template>
            {{ stateList[state]?stateList[state]:'BACKUP' }}
          </el-form-item>
          <el-divider content-position="left">{{$t('心跳口配置')}}</el-divider>
          <el-form-item :label="$t('接口')" prop="dev" style="width:400px">
            <el-select v-model="record.dev" :placeholder="$t('请选择')" size='small' filterable clearable @change="devChange($event, true)">
              <el-option :id="`hot-machine-dev-${index}`" v-for="(item,index) in physicalList" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('本端IP')" prop="dev_ip" style="width:400px">
            <el-select v-model="record.dev_ip" :placeholder="$t('请选择')" size='small' filterable>
              <el-option :id="`hot-machine-dev_ip-${key}`" v-for="(item, key) in devIpList" :key="key" :label="key" :value="key">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('对端IP')" prop="other_node_ip" style="width:400px">
            <el-input id="hot-machine-other_node_ip" v-emoji v-model="record.other_node_ip" style="width:217px;" size='small'></el-input>
          </el-form-item>
        </div>
        <div class="routerOutBorder" v-if="record.func_mode === 'AS'">
          <div class="routerOutBorder-title" :style="lang==='zh'?'width: 130px;':'width: 150px;'">
            <el-checkbox other_node_ip v-model="record.enable" :true-label='1' :false-label='0'>
            </el-checkbox>
            {{$t('路由模式')}}
          </div>
          <el-divider content-position="left">
            {{$t('热备口配置')}}
          </el-divider>
          <el-form-item :label="$t('接口')" prop="A_dev" style="width:400px">
            <el-select v-model="record.A_dev" :placeholder="$t('请选择')" size='small' filterable clearable @change='hotChange($event, "aipList")'>
              <el-option :id="`hot-machine-dev_ip-${index}`" v-for="(item,index) in physicalList" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('接口')" prop="B_dev" style="width:400px">
            <el-select v-model="record.B_dev" :placeholder="$t('请选择')" size='small' filterable clearable @change='hotChange($event, "bipList")'>
              <el-option :id="`hot-machine-B_dev-${index}`" v-for="(item,index) in physicalList" :key="item.strPhysicsName" :label="item.strPhysicsName" :value="item.strPhysicsName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('虚拟IP/掩码')" prop="A_ip" style="width:400px">
            <el-autocomplete id="hot-machine-A_ip" v-emoji v-model="record.A_ip" style="width:217px;" :fetch-suggestions="AipQuerySearch" size='small'></el-autocomplete>
          </el-form-item>
          <el-form-item :label="$t('虚拟IP/掩码')" prop="B_ip" style="width:400px">
            <el-autocomplete id="hot-machine-B_ip" v-emoji v-model="record.B_ip" style="width:217px;" :fetch-suggestions="BipQuerySearch" size='small'></el-autocomplete>
          </el-form-item>
          <el-divider content-position="left">{{$t('虚拟静态路由')}}</el-divider>
          <el-tabs v-model="activeName" type="card" @tab-click="hotMachineHandleClick" style="margin-bottom: 20px;">
            <el-tab-pane :label="$t('IPv4静态路由')" name="1">
              <el-button id="hot-machine-btn-add" type="success" size="mini" @click="addIpv4Click">{{$t('添加')}}</el-button>
              <el-table size='mini' ref="multipleTable" :data="ipv4List" tooltip-effect="dark" style="width: 100%">
                <el-table-column prop="ip-address" :label="$t('目的网络或主机')" align='center' min-width="120">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row['ip-address']" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="ip-mask" :label="$t('掩码')" align='center' min-width="120">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row['ip-mask']" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="interface" :label="$t('出接口')" align='center' min-width="120">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row.interface" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="nexthop" :label="$t('下一跳')" align='center' min-width="120">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row.nexthop" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="right" align='center' fixed="right" :label="$t('操作')" width="100">
                  <template slot-scope="scope">
                    <el-button id="hot-machine-btn-del" type="danger" plain size="mini" @click="deleteIpv4(scope.row)">{{$t('删除')}}</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane :label="$t('IPv6静态路由')" name="2">
              <el-button id="hot-machine-add" type="success" size="mini" @click="addIpv6Click">{{$t('添加')}}</el-button>
              <el-table size='mini' ref="multipleTable" :data="ipv6List" tooltip-effect="dark" style="width: 100%">
                <el-table-column prop="ip-address" :label="$t('目的网络或主机')" align='center' min-width="120">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row['ip-address']" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="ip-mask" :label="$t('IPv6前缀长度')" align='center' min-width="120">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row['ip-mask']" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="interface" :label="$t('出接口')" align='center' min-width="120">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row.interface" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="nexthop" :label="$t('下一跳')" align='center' min-width="120">
                  <template slot-scope="scope">
                    <tooltip :copyText="scope.row.nexthop" class="wid190">
                    </tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="right" align='center' fixed="right" :label="$t('操作')" width="100">
                  <template slot-scope="scope">
                    <el-button id="hot-machine-btn-del2" type="danger" plain size="mini" @click="deleteIpv6(scope.row)">{{$t('删除')}}</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form>
      <RealTimeConfigure ref="realTimeConfigureVisible" v-if="record.func_mode === 'AA'" @valueChange='valueChange'>
        <template slot="start-config">
          <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;margin-top:20px;">
            <div class="hotMachineButtonBox">
              <el-button @click="openCloseHotMachine('start')" type="primary" :loading='loading' v-if="hotState === '1'">{{$t('启动热备')}}</el-button>
              <el-button @click="openCloseHotMachine('stop')" type="danger" :loading='loading' v-if="hotState !== '1'">{{$t('关闭热备')}}</el-button>
              <el-button @click="useConfig" type="success">{{$t('应用配置')}}</el-button>
              <el-button @click="clearConfig" type="danger">{{$t('清空配置')}}</el-button>
            </div>
            <span style="color:red;">{{func_mode_text_map[record.func_mode]}}</span>
            <state-dialog v-if="dialogVisible" ref="refDialogVisible"></state-dialog>
          </div>
        </template>
      </RealTimeConfigure>
      <el-dialog :title="$t('是否开启bypass功能')" :v-if="dialogVisibleBypass" :visible.sync="dialogVisibleBypass" width="350px" top="20%">
        <div style="display: inline-flex;align-items: center;justify-content: center;width:100%;">
          <el-radio v-model="radioBypass" label="1">{{$t('是')}}</el-radio>
          <el-radio v-model="radioBypass" label="2">{{$t('否')}}</el-radio>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" @click="openCloseHotMachineBypass('stop')">{{$t('确 定')}}</el-button>
          <el-button size="small" @click="dialogVisibleBypass = false">{{$t('取 消')}}</el-button>
        </span>
      </el-dialog>
      <div v-if="record.func_mode !== 'AA'" style="display: flex;flex-direction: column;justify-content: center;align-items: center;margin-top:20px;">
        <div class="hotMachineButtonBox">
          <el-button @click="openCloseHotMachine('start')" type="primary" :loading='loading' v-if="hotState === '1'">{{$t('启动热备')}}</el-button>
          <el-button @click="openCloseHotMachine('stop')" type="danger" :loading='loading' v-if="hotState !== '1'">{{$t('关闭热备')}}</el-button>
          <el-button @click="useConfig" type="success">{{$t('应用配置')}}</el-button>
          <el-button @click="clearConfig" type="danger">{{$t('清空配置')}}</el-button>
        </div>
        <span style="color:red;">{{func_mode_text_map[record.func_mode]}}</span>
        <state-dialog v-if="dialogVisible" ref="refDialogVisible"></state-dialog>
      </div>
    </div>

    <Ipv4Dialog v-if="ipv4DialogVisible" ref="refIpv4DialogVisible"></Ipv4Dialog>
    <Ipv6Dialog v-if="ipv6DialogVisible" ref="refIpv6DialogVisible"></Ipv6Dialog>
  </div>
</template>
<script>
import {
  setHotMachineInfo,
  cleanHotMachineInfo,
  setHotMachineSwitch,
  getHotMachineRunStatus,
  getHotMachineInfo,
  getHotMachineStatus,
  getIpv4List,
  delIpv4,
  getIpv6List,
  delIpv6
} from '@/api/network/highAvailability/hotMachine'
import { getPhysicalApiArray, getPhysicalApiInfo } from '@/api/network/api/physical'
import { setBypassStatus } from '@/api/network/highAvailability/bypass'
import StateDialog from './StateDialog.vue'
import Ipv4Dialog from './components/Ipv4Dialog'
import Ipv6Dialog from './components/Ipv6Dialog'
import RealTimeConfigure from './components/RealTimeConfigure'
import Template from '../../../Safe/access/template/Template.vue'
export default {
  components: {
    StateDialog,
    Ipv4Dialog,
    Ipv6Dialog,
    RealTimeConfigure,
    Template },
  name: 'HotMachine',
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateDev = (rule, value, callback) => {
      if (rule.field === 'dev') {
        if (String(value).trim() === '') {
          callback(new Error(this.$t('不能为空')))
        } else if (this.record.dev === this.record.A_dev) {
          callback(new Error(this.$t('接口不能相同')))
        } else if (this.record.dev === this.record.B_dev) {
          callback(new Error(this.$t('接口不能相同')))
        }
      } else if (this.record.enable === 1) {
        if (String(value).trim() === '') {
          callback(new Error(this.$t('不能为空')))
        } else if (rule.field === 'A_dev' && this.record.dev === this.record.A_dev) {
          callback(new Error(this.$t('接口不能相同')))
        } else if (this.record.A_dev === this.record.B_dev) {
          callback(new Error(this.$t('接口不能相同')))
        } else if (rule.field === 'B_dev' && this.record.dev === this.record.B_dev) {
          callback(new Error(this.$t('接口不能相同')))
        }
      }
      callback()
    }
    var validateIp = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      }
      if (this.record.other_node_ip === this.record.dev_ip) {
        callback(new Error(this.$t('本端IP和对端IP不能相同')))
      }
      var flag = this.isEqualIPAddress(this.record.other_node_ip, this.record.dev_ip, this.devIpList[this.record.dev_ip])
      if (flag === true || flag === false) {
        callback()
      } else {
        callback(new Error(flag))
      }
    }
    var validateHotIp = (rule, value, callback) => {
      if (this.record.enable === 1) {
        if (String(value).trim() === '') {
          callback(new Error(this.$t('不能为空')))
        }
        var mask = value.split('/')[1]
        var ip = value.split('/')[0]
        // 判断ip格式是否正确
        if (!ip) {
          callback(new Error(this.$t('热备口虚拟 IP 不能为空')))
        }
        var exp4 = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
        var exp6 = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
        var ip_type = ''
        var ipv4Exp = ip.match(exp4)
        if (ipv4Exp) {
          ip_type = 'ipv4'
        }
        var ipv6Exp = ip.match(exp6)
        if (ipv6Exp) {
          ip_type = 'ipv6'
        }
        if (ip_type !== 'ipv4' && ip_type !== 'ipv6') {
          callback(new Error(this.$t('热备组的IP格式错误')))
        }
        // 判断掩码格式是否正确
        if (!mask) {
          callback(new Error(this.$t('热备口子网掩码不能为空')))
        }
        if (isNaN(Number(mask))) {
          callback(new Error(this.$t('掩码格式错误')))
        }
        if (ip_type === 'ipv4' && (Number(mask) > 32 || Number(mask) < 1)) {
          callback(new Error(this.$t('Ipv4 的掩码取值范围为 1-32')))
        }
        if (ip_type === 'ipv6' && (mask > 128 || mask < 1)) {
          callback(new Error(this.$t('IPv6 的掩码取值范围为 1-128')))
        }

        // 热备组一和热备组二 IP 类型必须一致
        var A_ip = this.record.A_ip.split('/')[0]
        var B_ip = this.record.B_ip.split('/')[0]
        var A_mask = this.record.A_ip.split('/')[1]
        var B_mask = this.record.B_ip.split('/')[1]
        var A_ip_type = A_ip.match(exp4) ? 'ipv4' : (A_ip.match(exp6) ? 'ipv6' : '')
        var B_ip_type = B_ip.match(exp4) ? 'ipv4' : (B_ip.match(exp6) ? 'ipv6' : '')
        if (A_ip_type && B_ip_type && A_ip_type !== B_ip_type) {
          callback(new Error(this.$t('热备组一和热备组二 IP 类型必须一致')))
        }

        // 如果热备组的IP是ipv4类型的则需要和心跳组的IP进行判断是否是同网段的
        if (ip_type === 'ipv4') {
          var flag = this.isEqualIPAddress(ip, this.record.dev_ip, this.devIpList[this.record.dev_ip])
          if (flag === true) {
            callback(new Error(this.$t('热备组和心跳组IP不能是同一网段')))
          }
          var mask_complete = this.maskConversion(mask)
          if (this.isEqualIPAddress(A_ip, B_ip, mask_complete) === true) {
            callback(new Error(this.$t('热备组两个IP不能是同一网段')))
          }
        } else {
          var little_mask = A_mask < B_mask ? A_mask : B_mask
          if (this.ipv6InSubnet(A_ip, B_ip, little_mask)) {
            callback(new Error(this.$t('热备组两个IP不能是同一网段')))
          }
        }
      }
      callback()
    }
    return {
      lang: this.$i18n.locale,
      func_mode_text_map:{
        AS:this.$t('提示：开启时请先开启主模式下的热备'),
        AA:this.$t('提示：勾选实时同步选项并启动热备功能后，系统将自动执行配置对比和同步操作，请耐心等待')
      },
      dialogVisible: false,
      ipv4DialogVisible: false,
      ipv6DialogVisible: false,
      dialogVisibleBypass: false,
      radioBypass: '1',
      activeName: '1',
      record: {
        func_mode: 'AS',
        run_mode: 'PREEMPT',
        node: 'MASTER',
        dev: '',
        dev_ip: '',
        other_node_ip: '',
        enable: 0,
        A_dev: '',
        A_ip: '',
        B_dev: '',
        B_ip: '',
        sync: 'disable',
        security: 'disable',
        network: 'disable'
      },
      stateArray: {
        '0': this.$t('开启'),
        '1': this.$t('关闭')
      },
      hotState: '0',
      state: '0',
      stateList: {
        '0': this.$t('未启用'),
        '1': 'MASTER',
        '2': 'BACKUP',
        '3': 'READY',
        '4': 'FAULT'
      },
      funcModeList: { 'AS': this.$t('主备模式'), 'AA': this.$t('连接保护模式') },
      runModeList: { 'PREEMPT': this.$t('抢占') },
      physicalList: [],
      devIpList: {},
      ipv4List: [],
      ipv6List: [],
      ipList: {
        aipList: [],
        bipList: []
      },
      loading: false,
      timer: null,
      realTimeShow: false,
      nowMode: 'AS', // 保存配置时的状态
      rules: {
        dev: [{ required: false, validator: validateDev, trigger: 'change' }],
        dev_ip: [{ required: false, validator: validateName, trigger: 'change' }],
        other_node_ip: [{ required: false, validator: validateIp, trigger: 'blur' }],
        A_dev: [{ required: false, validator: validateDev, trigger: 'change' }],
        B_dev: [{ required: false, validator: validateDev, trigger: 'change' }],
        A_ip: [{ required: false, validator: validateHotIp, trigger: 'blur' }],
        B_ip: [{ required: false, validator: validateHotIp, trigger: 'blur' }]
      }
    }
  },
  watch: {
    state () {
      this.loading = false
    }
  },
  mounted () {
    this.listData()
  },
  beforeDestroy () {
    if (this.timer) {
      clearInterval(this.timer) // 在Vue实例销毁前，清除我们的定时器
      this.timer = null
    }
  },
  methods: {
    // 列表
    listData () {
      Promise.all([getHotMachineRunStatus(), getHotMachineInfo()]).then(res => {
        if (res[0].status === 0) {
          this.hotState = res[0].info[0].state
        }
        if (res[1].status === 0) {
          this.record = Object.assign(this.record, res[1].info[0])
          if(!res[1].info[0].node) {
            this.record.node = 'MASTER';
          }
          this.nowMode = res[1].info[0].func_mode
          this.funcModeChange(this.record.func_mode)
          this.record.run_mode = 'PREEMPT'
          this.record.node = (this.record.node === 'CONNECT' ? 'MASTER' : this.record.node)
          switch (res[1].info[0].configitem) {
            case '1':
              this.record.network = 'enable'
              this.record.security = 'disable'
              break
            case '2':
              this.record.network = 'disable'
              this.record.security = 'enable'
              break
            case '3':
              this.record.network = 'enable'
              this.record.security = 'enable'
              break
            case '0':
              this.record.network = 'disable'
              this.record.security = 'disable'
              break
          }
          if (this.record.func_mode === 'AS') {
            this.hotMachineHandleClick()
            if (this.record.A_ip) {
              this.record.A_ip = res[1].info[0].A_ip ? res[1].info[0].A_ip + '/' + res[1].info[0].A_mask : res[1].info[0].A_ip
            }
            if (this.record.B_ip) {
              this.record.B_ip = res[1].info[0].B_ip ? res[1].info[0].B_ip + '/' + res[1].info[0].B_mask : res[1].info[0].B_ip
            }
          }
          if (this.record.dev) {
            this.devChange(this.record.dev, false)
          }
        }
      })
      getPhysicalApiArray().then(res => {
        if (res.status === 0) {
          this.physicalList = res.info
        }
      })
    },
    funcModeChange (data) {
      if (this.nowMode === 'AA' && data === 'AA') {
        this.realTimeShow = true
        this.$nextTick(() => {
          this.$refs.realTimeConfigureVisible.init(this.record)
        })
      } else if (data === 'AS') {
        if (this.timer === null) {
          this.hotMachineStatusOpen()
          this.timer = setInterval(() => {
            this.hotMachineStatusOpen()
          }, 3000)
        }
      }
      if (data === 'AA') {
        if (this.timer) {
          clearInterval(this.timer) // 在Vue实例销毁前，清除我们的定时器
          this.timer = null
        }
      }
    },
    stateClick () {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.refDialogVisible.init()
      })
    },
    hotMachineStatusOpen () {
      getHotMachineStatus().then(res => {
        if (res.status === 0) {
          this.state = res.info[0].state
        }
      }).catch(e => {
        clearInterval(this.timer)
        this.timer = null
      })
    },
    devChange (data, flag) {
      if (flag) {
        this.record.dev_ip = ''
        this.$nextTick(() => {
          this.$refs.form.clearValidate(['dev_ip'])
        })
      }
      if (data) {
        getPhysicalApiInfo({ name: data }).then(res => {
          if (res.status === 0) {
            this.devIpList = {}
            if (res.info[0].ipv4 && res.info[0].ipv4.length > 0) {
              res.info[0].ipv4.forEach(item => {
                if (item.cPortNetmask) {
                  this.devIpList[item.cPortIpv4] = item.cPortNetmask
                }
              })
            }
          }
        })
      } else {
        this.devIpList = {}
      }
    },
    /**
     * [hotChange 选择接口时给对应列表增加数据]
     * @param  {[String]}  data [接口值]
     * @param  {[String]}  listName [对应列表名称]
     */
    hotChange (data, listName) {
      this.ipList[listName] = []
      if (data) {
        getPhysicalApiInfo({ name: data }).then(res => {
          if (res.status === 0) {
            if (res.info[0].ipv4 && res.info[0].ipv4.length > 0) {
              res.info[0].ipv4.forEach(item => {
                if (item.cPortNetmask) {
                  this.ipList[listName].push({'value': item.cPortIpv4})
                }
              })
            }
          }
        })
      }
    },
    /**
     * [AipQuerySearch 虚拟IP/掩码提示数据函数]
     * @param  {[String]}  queryString [虚拟IP/掩码值]
     * @param  {[Object]}  callback [返回提示列表]
     */
    AipQuerySearch (queryString, callback) {
      let resList = this.ipList.aipList
      let results = queryString ? resList.filter(item => item.value.includes(queryString)) : resList
      callback(results)
    },
    BipQuerySearch (queryString, callback) {
      let resList = this.ipList.bipList
      let results = queryString ? resList.filter(item => item.value.includes(queryString)) : resList
      callback(results)
    },
    openCloseHotMachine (state) {
      if (state === 'start') {
        const textMsg = this.record.func_mode === 'AA' ? this.$t('在启动流程中，首先启动端点将自动接收来自对端的同步配置信息') : this.$t('开启双机热备,自动关闭bypass功能')
        this.$confirm(textMsg, this.$t('信息'), {
          closeOnClickModal: false,
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          cancelButtonClass: 'confirmCancelButton',
          type: 'warning'
        }).then(() => {
          this.loading = true
          setBypassStatus({ status: 'off' }).then(() => {
            setHotMachineSwitch({ state: state, func_mode: this.record.func_mode }).then(res => {
              this.$messages.success(res.msg)
              getHotMachineRunStatus().then(res => {
                if (res.status === 0) {
                  this.hotState = res.info[0].state
                }
              })
              this.loading = false
              if (this.nowMode === 'AA') {
                this.realTimeShow = true
              }
            }).catch(e => {
              this.loading = false
            })
          })
        })
      } else {
        this.dialogVisibleBypass = true
      }
    },
    openCloseHotMachineBypass (state) {
      this.loading = true
      setHotMachineSwitch({ state: state, func_mode: this.record.func_mode }).then(res => {
        this.$messages.success(res.msg)
        setBypassStatus({ status: this.radioBypass === '1' ? 'on' : 'off' })
        getHotMachineRunStatus().then(res => {
          this.hotState = res.info[0].state
        })
        this.realTimeShow = false
        this.loading = false
        this.dialogVisibleBypass = false
      }).catch(e => {
        this.loading = false
        this.dialogVisibleBypass = false
      })
    },
    useConfig () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let formData = JSON.parse(JSON.stringify(this.record))
          if (formData.func_mode === 'AA') {
            formData.node = 'CONNNECT'
          }
          setHotMachineInfo(formData).then(res => {
            if (res.status === 0) {
              this.$messages.success(res.msg)
              this.listData()
            }
          })
        }
      })
    },
    clearConfig () {
      this.$confirm(this.$t('您是否要清空配置?'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        cleanHotMachineInfo().then(res => {
          if (res.status === 0) {
            this.$messages.success(res.msg)
            this.listDataClear().then(() => {
              this.$refs['form'].clearValidate()
              this.devIpList = {}
            })
            this.hotMachineHandleClick()
          }
        })
      })
    },
    listDataClear () {
      return new Promise((resolve, reject) => {
        Promise.all([getHotMachineRunStatus(), getHotMachineInfo(), getPhysicalApiArray()]).then(res => {
          if (res[0].status === 0) {
            this.hotState = res[0].info[0].state
          }
          if (res[1].status === 0) {
            this.record = Object.assign(this.record, res[1].info[0])
            this.nowMode = res[1].info[0].func_mode
            this.record.run_mode = 'PREEMPT'
            this.record.node = this.record.node ? this.record.node : 'MASTER'
            this.record.A_dev = ''
            this.record.B_dev = ''
            this.record.enable = 0
            switch (res[1].info[0].configitem) {
              case '1':
                this.record.network = 'enable'
                this.record.security = 'disable'
                break
              case '2':
                this.record.network = 'disable'
                this.record.security = 'enable'
                break
              case '3':
                this.record.network = 'enable'
                this.record.security = 'enable'
                break
              case '0':
                this.record.network = 'disable'
                this.record.security = 'disable'
                break
            }
            if (this.record.A_ip) {
              this.record.A_ip = res[1].info[0].A_ip ? res[1].info[0].A_ip + '/' + res[1].info[0].A_mask : res[1].info[0].A_ip
            } else {
              this.record.A_ip = ''
            }
            if (this.record.B_ip) {
              this.record.B_ip = res[1].info[0].B_ip ? res[1].info[0].B_ip + '/' + res[1].info[0].B_mask : res[1].info[0].B_ip
            } else {
              this.record.B_ip = ''
            }
            if (this.record.dev) {
              this.devChange(this.record.dev)
            }
          }
          if (res[2].status === 0) {
            this.record = Object.assign(this.record, res[2].info[0])
            this.record.run_mode = 'PREEMPT'
            this.record.node = this.record.node ? this.record.node : 'MASTER'
            if (this.record.A_ip) {
              this.record.A_ip = res[2].info[0].A_ip ? res[2].info[0].A_ip + '/' + res[2].info[0].A_mask : res[2].info[0].A_ip
            }
            if (this.record.B_ip) {
              this.record.B_ip = res[2].info[0].B_ip ? res[2].info[0].B_ip + '/' + res[2].info[0].B_mask : res[2].info[0].B_ip
            }
            if (this.record.dev) {
              this.devChange(this.record.dev)
            }
          }
          resolve()
        })
      })
    },
    hotMachineHandleClick () {
      switch (this.activeName) {
        case '1':
          getIpv4List().then(res => {
            if (res.status === 0) {
              this.ipv4List = res.info
            }
          })
          break
        case '2':
          getIpv6List().then(res => {
            if (res.status === 0) {
              this.ipv6List = res.info
            }
          })
          break
      }
    },
    deleteIpv4 (row) {
      this.$confirm(this.$t('您是否要删除该数据？'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        let form = {
          ip_address: row['ip-address'],
          ipv4_mask: row['ip-mask'],
          interface: row.interface
        }
        delIpv4(form).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('删除成功'))
            this.hotMachineHandleClick()
          }
        })
      })
    },
    deleteIpv6 (row) {
      this.$confirm(this.$t('您是否要删除该数据？'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        let form = {
          ipv6_address: row['ip-address'],
          prefix_len: row['ip-mask'],
          interface: row.interface
        }
        delIpv6(form).then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t('删除成功'))
            this.hotMachineHandleClick()
          }
        })
      })
    },
    addIpv4Click () {
      this.ipv4DialogVisible = true
      this.$nextTick(() => {
        this.$refs.refIpv4DialogVisible.init()
      })
    },
    addIpv6Click () {
      this.ipv6DialogVisible = true
      this.$nextTick(() => {
        this.$refs.refIpv6DialogVisible.init()
      })
    },
    /**
     * [isEqualIPAddress 判断两个IP地址是否在同一个网段]
     * @param  {[String]}  addr1 [地址一]
     * @param  {[String]}  addr2 [地址二]
     * @param  {[String]}  mask  [子网掩码]
     * @return {Boolean}         [true or false]
     */
    isEqualIPAddress (addr1, addr2, mask) {
      if (!addr1 || !addr2 || !mask) {
        return false
      }
      var res1 = []
      var res2 = []
      addr1 = addr1.split('.')
      addr2 = addr2.split('.')
      mask = mask.split('.')
      for (var i = 0, ilen = addr1.length; i < ilen; i += 1) {
        res1.push(parseInt(addr1[i]) & parseInt(mask[i]))
        res2.push(parseInt(addr2[i]) & parseInt(mask[i]))
      }
      if (res1.join('.') === res2.join('.')) {
        // 在同一个网段
        return true
      } else {
        return this.$t('不在同一个网段')
      }
    },
    ipv6InSubnet (ipv6Addr1, ipv6Addr2, prefixLength) {
      if (!ipv6Addr1 || !ipv6Addr2 || !prefixLength) {
        return false
      }
      // 将IPv6地址转换为二进制格式
      const ipv6Binary1 = this.ipv6ToBinary(ipv6Addr1)
      const ipv6Binary2 = this.ipv6ToBinary(ipv6Addr2)
      // 获取前缀长度（即子网掩码位数）
      const prefixLen = parseInt(prefixLength)
      // 判断是否在同一网段中
      for (let i = 0; i < prefixLen; i++) {
        if (ipv6Binary1[i] !== ipv6Binary2[i]) {
          return false
        }
      }
      return true
    },
    ipv6ToBinary (ipv6Addr) {
      // 将IPv6地址转换为16进制数组
      const hexArray = ipv6Addr.split(':')
      // 将每个16进制数字转换为二进制字符串，并拼接起来
      let binaryStr = ''
      for (let i = 0; i < hexArray.length; i++) {
        const hexStr = hexArray[i]
        const binStr = parseInt(hexStr, 16).toString(2).padStart(16, '0')
        binaryStr += binStr
      }
      // 返回二进制字符串的数组
      return binaryStr.split('')
    },
    maskConversion (value) {
      var str = '11111111111111111111111111111111'.slice(0, value - 1).toString() + '00000000000000000000000000000000'.slice(value - 1, 31).toString()
      var result = []
      for (var i = 0; i < 32; i = i + 8) {
        var s = str.slice(i, i + 7)
        result.push(parseInt(s, 2))
      }
      // alert(result.join("."));
      return result.join('.')
    },
    valueChange (value) {
      this.record[value.key] = value.value
    }
  }
}
</script>
<style lang="less">
.HotMachineCollapse {
  margin: 20px auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow-x: auto;
  .el-collapse-item__header {
    font-size: 18px;
    font-weight: 600;
  }
  .el-collapse-item__content {
    margin-left: 20px;
  }
}
</style>
<style lang="less" scoped>
.HotMachineCollapse {
  .el-divider__text {
    font-size: 20px;
  }
  .el-divider {
    margin: 40px 0;
  }
}
.el-form-item {
  padding: 0 20px;
}
.hotMachineButtonBox {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.stateIcon {
  color: #e6a23c;
  font-size: 16px;
  margin-left: 5px;
  cursor: pointer;
}
.routerOutBorder {
  margin-top:20px;
  border: 1px solid #DCDFE6;
  padding: 0 30px;
}
.routerOutBorder-title {
  height: 30px;
  line-height: 30px;
  background: white;
  text-align: center;
  margin-top: -16px;
  margin-left: 10px;
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}
</style>